package cn.hefan.web.servlet.login;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;

import cn.hefan.domain.Admin;
import cn.hefan.domain.ResultInfo;
import cn.hefan.service.LoginService;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {


	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//解决中午乱码问题
		request.setCharacterEncoding("UTF-8");
		//获取数据
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		Admin admin = LoginService.adminLogin(username,password);
		ResultInfo info = new ResultInfo();
		if(admin!=null) {
			request.getSession().setAttribute("admin",admin);//登录成功标记
			info.setFlag(true);		
		}else {
			info.setFlag(false);
			info.setErrorMsg("用户名或密码错误");
		}
		//响应数据
		ObjectMapper mapper = new ObjectMapper();
		
		response.setContentType("application/json;charset=utf-8");
		mapper.writeValue(response.getOutputStream(),info);
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
